//
//  HCHomeViewModel.swift
//  新浪微博
//
//  Created by fanhoucheng on 16/9/27.
//  Copyright © 2016年 fanhoucheng. All rights reserved.
//

import UIKit
import YYModel

class HCHomeViewModel: NSObject {
    
    lazy var statusViewModelArray: [HCStatusViewModel] = [HCStatusViewModel]()
    
    func loadHomeModel(isPullup: Bool, finished: @escaping (Bool, Int) -> ()) {
        var access_token = ["access_token" : HCUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token ?? ""]
        if isPullup {
            access_token["max_id"] = "\((statusViewModelArray.last?.status?.id ?? 0) - 1)"
        } else {
            //如果下拉刷新
            access_token["since_id"] = "\(statusViewModelArray.first?.status?.id ?? 0)"
        }
        
        HMNetworkTools.sharedTools.request(method: .GET, urlString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: access_token) { (responseObject, error) in
            
            //判断错误
            if (error != nil) {
                finished(false, 0)
                return
            }
            //获取微博信息
            let dict = responseObject as! [String: Any]
            let array = dict["statuses"] as? [[String: Any]]
            guard (array != nil) else {
                return
            }
            
            var tempArray: [HCStatusViewModel] = [HCStatusViewModel]()
            //数组中的字典全部遍历出来
            for item in array! {
                //字典item转模型
                let status = HCStatus()
                let statusViewModel = HCStatusViewModel()
                status.yy_modelSet(with: item)
                statusViewModel.status = status
                tempArray.append(statusViewModel)
            }
            
            if isPullup {
                self.statusViewModelArray = self.statusViewModelArray + tempArray
            } else {
                self.statusViewModelArray = tempArray + self.statusViewModelArray
            }
            
            finished(true, tempArray.count)
        }
    }

}
